<template>
    <div>
        <!-- 搜索栏 -->
        <el-card class="!border-none mb-4" shadow="never">
            <el-form class="mb-[-16px]" :model="queryParams" :inline="true">
                <el-form-item label="文档名称">
                    <div class="w-[250px]">
                        <el-input
                            v-model="queryParams.name"
                            placeholder="请输入文档名称"
                            clearable
                            @keyup.enter="resetPaging"
                        />
                    </div>
                </el-form-item>
                <el-form-item label="文档编号">
                    <div class="w-[250px]">
                        <el-input
                            v-model="queryParams.code"
                            placeholder="请输入文档编号"
                            clearable
                            @keyup.enter="resetPaging"
                        />
                    </div>
                </el-form-item>
                <el-form-item label="用户编号">
                    <div class="w-[250px]">
                        <el-input
                            v-model="queryParams.user"
                            placeholder="请输入用户编号"
                            clearable
                            @keyup.enter="resetPaging"
                        />
                    </div>
                </el-form-item>
                <el-form-item label="解析状态">
                    <div class="w-[180px]">
                        <el-select
                            v-model="queryParams.status"
                            placeholder="全部"
                        >
                            <el-option value="" label="全部"/>
                            <el-option value="0" label="待解析"/>
                            <el-option value="1" label="排队中"/>
                            <el-option value="2" label="解析中"/>
                            <el-option value="3" label="解析完成"/>
                            <el-option value="4" label="解析失败"/>
                        </el-select>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="resetPaging">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 表格栏 -->
        <el-card v-loading="pager.loading" class="!border-none" shadow="never">
            <el-table :data="pager.lists" size="large" class="mt-4">
                <el-table-column label="ID" prop="id" width="100" />
                <el-table-column label="来源用户" prop="user" width="200">
                    <template #default="{ row }">
                        <div class="flex items-center">
                            <el-avatar :size="38" :src="row?.user?.avatar"/>
                            <div class="ml-2">
                                <div class="text-sm">{{ row?.user?.nickname }}</div>
                                <div class="text-xs text-tx-placeholder">{{ row?.user?.sn }}</div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="文档名称" min-width="100">
                    <template #default="{ row }">
                        <div class="flex items-center">
                            <el-image
                                :src="suffixUtil.findUnitIcon(row.ext)"
                                class="w-[34px] h-[38px] shrink-0"
                            />
                            <p class="ml-1.5">{{ row?.name }}</p>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="扩展名称" prop="ext" width="100" />
                <el-table-column label="文件大小" prop="size" width="120">
                    <template #default="{ row }">
                        {{ formatBytes(row?.size) }}
                    </template>
                </el-table-column>
                <el-table-column label="解析模型" prop="vector_alias" width="120" />
                <el-table-column label="来源IP" prop="ip" width="100" />
                <el-table-column label="状态" prop="status" width="100">
                    <template #default="{ row }">
                        <el-tag v-if="row.status === 0" type="info">待解析</el-tag>
                        <el-tag v-if="row.status === 1" type="warning">解析中</el-tag>
                        <el-tag v-if="row.status === 2" type="success">解析完成</el-tag>
                        <el-tooltip v-if="row.status === 3" effect="dark" placement="top">
                            <el-tag
                                type="danger"
                                class="cursor-pointer"
                                @click="handleRetry(row.id)"
                            >
                                解析失败
                            </el-tag>
                            <template #content>
                                <div class="max-w-[600px]">{{ row?.error || '-'}}</div>
                            </template>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column label="上传时间" prop="create_time" width="180" />
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <el-button
                            type="primary"
                            link
                            @click="handleDataset(row)"
                        >
                            文档数据
                        </el-button>
                        <el-button
                            type="warning"
                            link
                            @click="handleDownload(row.raw_path, row.name)"
                        >
                            下载
                        </el-button>
                        <el-button
                            v-perms="['apply:docs:files:delete']"
                            type="danger"
                            link
                            @click="handleDelete(row.id)"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-end mt-4">
                <paging v-model="pager" @change="queryLists" />
            </div>
        </el-card>

        <!-- 编辑器 -->
        <dataset v-if="showDataset" ref="datasetRef" @close="showDataset = false" />
    </div>
</template>

<script setup lang="ts">
import { usePaging } from '@/hooks/usePaging.ts'
import feedback from '@/utils/feedback.ts'
import toolsUtil from '@/utils/tools.ts'
import suffixUtil from '@/utils/suffix.ts'
import docsFilesApi from '@/api/apply/docs/files.ts'
import Dataset from './dataset.vue'

// 数据弹窗
const showDataset = ref(false)
const datasetRef = shallowRef<InstanceType<typeof Dataset>>()

// 查询参数
const queryParams = reactive({
    status: '',
    code: '',
    name: '',
    user: ''
})

// 分页查询
const { pager, queryLists, resetParams, resetPaging } = usePaging({
    fetchFun: docsFilesApi.lists,
    params: queryParams
})

/**
 * 格式化大小
 *
 * @param {number} size
 * @return {string}
 */
const formatBytes = (size: number): string => {
    return toolsUtil.formatBytes(size)
}

/**
 * 处理下载
 *
 * @param {string} fileUrl
 * @param {string} filename
 */
const handleDownload = async (fileUrl: string, filename: string) => {
    const link = document.createElement('a')
    link.target = '_blank'
    link.href = fileUrl
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
}

/**
 * 处理编辑
 *
 * @param {any} row
 * @returns {Promise<void>}
 */
const handleDataset = async (row?: any): Promise<void> => {
    showDataset.value = true
    await nextTick()
    datasetRef.value?.open(row)
}

/**
 * 处理删除
 *
 * @param {number} id
 * @returns {Promise<void>}
 */
const handleDelete = async (id: number): Promise<void> => {
    feedback.confirm('确定要删除此项数据吗?')
        .then(async () => {
            await docsFilesApi.delete(id)
            feedback.msgSuccess('删除成功')
            await queryLists()
        }).catch(() => {})
}

/**
 * 处理重试
 */
const handleRetry = async (id: number): Promise<void> => {
    feedback.confirm('确定要重试训练吗?')
        .then(async () => {
            await docsFilesApi.retry(id)
            feedback.msgSuccess('发起成功')
            await queryLists()
        }).catch(() => {})
}

onMounted(async () => {
    await queryLists()
})
</script>
